function varargout = TLRateLimiterDlg(action,varargin)

% TL_RATELIMITER_DLG manages the user interface for TargetLink Rate Limiter block
%
% SYNTAX dlgInfo = tl_constant_dlg('GetDlgInfo');
%   gets dialog info of TargetLink Rate Limiter block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = tl_constant_dlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = tl_constant_dlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = tl_constant_dlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = tl_constant_dlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX tl_constant_dlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLRatelimiterDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.17 $
% $Date: 2011/07/21 14:17:29MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action

    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Rate Limiter';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames = {
            'Output';
            'Slew Rates';
            'Logging & Autoscaling';
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Output'
                excludedCtrls = {'inheritproperties'};
                [sheetDims, ctrlPos] = tl_calc_ctrls_positions(commonGeom, excludedCtrls);

            case 'Slew Rates'
                [sheetDims, ctrlPos] = FcnSlewRatesCtrlPositions(commonGeom);

            case 'Logging & Autoscaling'
                excludedCtrls = {};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims, ctrlPos] = ...
                    TLManageDocCtrls('ctrlpos', commonGeom, sheetDims, bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                % create all controls
                dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
                dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

            case 'Slew Rates'
                dlgdata = FcnCreateSlewRatesControls(pageNum, dlgfig, dlgdata);

            case 'Logging & Autoscaling'
                enable = 1;
                dlgdata = TLManageLoggingCtrls('create', pageNum, dlgfig, dlgdata, enable);

            case 'Documentation'
                dlgdata = TLManageDocCtrls('create', pageNum, dlgfig, dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
        switch pageName
            case 'Output'
                [dlgdata, bModified1] = ...
                    TLManageVariableCtrls('manage',pageNum,dlgfig,dlgdata,pageAction,'output');
                [dlgdata, bModified2] = ...
                    TLManageScalingCtrls('manage',pageNum,dlgfig,dlgdata,pageAction,'output');
                bModified = bModified1 || bModified2;

            case 'Slew Rates'
                [dlgdata,bModified] = ...
                    FcnManageSlewRatesControls(pageNum,dlgfig,dlgdata,pageAction);

            case 'Logging & Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');

            case 'Documentation'
                [dlgdata, bModified] = ...
                    TLManageDocCtrls('callback', pageNum, dlgfig, dlgdata, pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified ;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};

        pageName  = dlgdata.pageNames{pageNum};

        switch pageName
            case 'Output'
                % update all controls
                dlgdata = TLManageVariableCtrls('update',pageNum,dlgdata,'output');
                dlgdata = TLManageScalingCtrls('update',pageNum,dlgdata,'output', []);

                % set controls
                TLManageVariableCtrls('setCtrls',pageNum,dlgfig,dlgdata);
                TLManageScalingCtrls('setCtrls',pageNum,dlgfig,dlgdata);

            case 'Slew Rates'
                dlgdata = FcnUpdateSlewRatesControls(dlgdata, dlgfig, pageNum);

            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);

            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action "' action '"']);

end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        switch dlgdata.pageNames{dlgdata.CurrentPageNum}
            case 'Slew Rates'
                blockVar{1} = 'fslewrate';
                blockVar{2} = 'rslewrate';
                idx = get(dlgdata.pageData{2}.children.selectPopup,'Value');
                tl_create_links_to_model('ShowDeclaration',dlgdata.model, blockVar{idx});
            otherwise
                blockVar = 'output';
                tl_create_links_to_model('ShowComputation',dlgdata.model, blockVar);
        end

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnSlewRatesCtrlPositions calculates positions for slew rate controls
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnSlewRatesCtrlPositions(commonGeom)

excludedCtrls = {'calcranges', 'saturate', 'inheritproperties'};
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = {...
    'Select:',           'text';
    'Falling:',          'text';
    'Maximum accuracy',  'checkbox';
    'Scalar',            'checkbox';
    'Scale Slew Rate ',  'pushbutton';
    'Use value of Data Dictionary variable', 'checkbox'};

[selectLabelSize, ...
    rateLabelSize, ...
    maxAccuracyCheckboxSize, ...
    scalarCheckboxSize, ...
    autoscaleButtonSize, ...
    useDDValueCheckboxSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

%-----------------------------------------------------------
% enlarge groupboxes
%-----------------------------------------------------------

% calculate extra space needed for select popup
dy = commonGeom.editHeight + rowDelta;

% enlarge tlcgGroupbox and move addoptGroupbox
ctrlPos.tlcgoptGroupbox(4) = ctrlPos.tlcgoptGroupbox(4) + dy;
ctrlPos.addoptGroupbox(2)  = ctrlPos.addoptGroupbox(2)  + dy;

% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = commonGeom.editHeight ...
    + 2 * commonGeom.checkboxHeight ...
    + 2 * rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

%-----------------------------------------------------------
% supplement tlcgGroupbox
%-----------------------------------------------------------

cy = ctrlPos.descLabel(2) + commonGeom.editHeight + rowDelta;

% select label
cx = col(1);
ctrlPos.selectLabel = [cx cy selectLabelSize];

% select popup
cx = col(2);
ctrlPos.selectPopup = [cx cy ctrlPos.lsbEdit(3:4)];

% slew rate autoscale button
cx = cx + ctrlPos.selectPopup(3) + colDelta / 3;
ctrlPos.scaleSlewRateButton = [cx,cy, autoscaleButtonSize];

%---------------------------------------
% 3rd row
cy = commonGeom.frameBottomEdgeBuffer;

% ddv checkbox associated with falling slewrate
cx = col(2);
ctrlPos.fslewrateDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

% ddv checkbox associated with rising slewrate
cx = col(4);
ctrlPos.rslewrateDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

%---------------------------------------
% 2nd row
cy = cy + commonGeom.checkboxHeight + rowDelta;

% falling slew rate scalar checkbox
cx = col(2);
ctrlPos.fallingRateScalarCheckbox = [cx cy scalarCheckboxSize];

% rising slew rate scalar checkbox
cx = col(4);
ctrlPos.risingRateScalarCheckbox = [cx cy scalarCheckboxSize];

%---------------------------------------
% 1st row
cy = cy + commonGeom.checkboxHeight + rowDelta;

% falling rate label
cx = col(1);
ctrlPos.fallingRateLabel = [cx cy rateLabelSize];

% falling rate edit field
cx = col(2);
ctrlPos.fallingRateEdit = [cx cy ctrlPos.lsbEdit(3:4)];

% rising rate label
cx = col(4) - rateLabelSize(1) - colDelta / 3;
ctrlPos.risingRateLabel = [cx cy rateLabelSize];

% rising rate edit field
cx = col(4);
ctrlPos.risingRateEdit = [cx cy ctrlPos.lsbEdit(3:4)];

% maximum accuracy checkbox
cx = ctrlPos.addoptGroupbox(3) - ctrlPos.addoptGroupbox(1) - maxAccuracyCheckboxSize(1);
ctrlPos.maxAccuracyCheckbox = [cx cy maxAccuracyCheckboxSize];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight ...
    + dy;


%-----------------------------------------------------------------------------------------
% FcnCreateSlewRatesControls creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateSlewRatesControls(pageNum, dlgfig, dlgdata)

% create controls for falling slew rate initially
dlgdata = TLManageVariableCtrls('create', pageNum, dlgfig, dlgdata);
dlgdata = TLManageScalingCtrls('create', pageNum, dlgfig, dlgdata);

Children = dlgdata.pageData{pageNum}.children;
ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;
pageName = dlgdata.pageNames{pageNum};

% variable select controls
Children.selectLabel = uicontrol( ...
    'Parent',             Children.tlcgoptGroupbox, ...
    'String',             'Select:', ...
    'Style',              'text', ...
    'Position',           ctrlPos.selectLabel);

Children.selectPopup = uicontrol( ...
    'Parent',             Children.tlcgoptGroupbox, ...
    'Style',              'Popupmenu', ...
    'String',             {'falling slew rate' 'rising slew rate'}, ...
    'BackgroundColor',    'w', ...
    'Position',           ctrlPos.selectPopup, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''selectPopup'')',pageName));

% create the addoptGroupbox which will contain slew rate controls
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Slew Rates'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% variable value controls
Children.fallingRateLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'String',             'Falling:', ...
    'Style',              'text', ...
    'Position',           ctrlPos.fallingRateLabel);

Children.fallingRateEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'edit', ...
    'BackgroundColor',    'w', ...
    'Position',           ctrlPos.fallingRateEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''fallingRateEdit'')',pageName));

Children.risingRateLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'String',             'Rising:', ...
    'Style',              'text', ...
    'Position',           ctrlPos.risingRateLabel);

Children.risingRateEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'edit', ...
    'BackgroundColor',    'w', ...
    'Position',           ctrlPos.risingRateEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''risingRateEdit'')',pageName));

Children.maxAccuracyCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Maximum accuracy', ...
    'Position',           ctrlPos.maxAccuracyCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''maxAccuracyCheckbox'')',pageName));

Children.fallingRateScalarCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Scalar', ...
    'Position',           ctrlPos.fallingRateScalarCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''fallingRateScalarCheckbox'')',pageName));

Children.risingRateScalarCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Scalar', ...
    'Position',           ctrlPos.risingRateScalarCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''risingRateScalarCheckbox'')',pageName));

Children.scaleSlewRateButton = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'pushbutton', ...
    'String',             'Scale Slew Rate', ...
    'Position',           ctrlPos.scaleSlewRateButton, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''scaleSlewRateButton'')',pageName));

Children.fslewrateDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.fslewrateDDValueCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''fslewrateDDValueCheckbox'')',pageName));

Children.rslewrateDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.rslewrateDDValueCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''rslewrateDDValueCheckbox'')',pageName));

dlgdata.pageData{pageNum}.children = Children;


%-----------------------------------------------------------------------------------------
% FcnManageSlewRatesControls manage control actions of slew rate page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSlewRatesControls(pageNum, dlgfig, dlgdata, pageAction)

bModified  = 0;
Children   = dlgdata.pageData{pageNum}.children;
fieldIdx   = get(Children.selectPopup, 'Value');

switch fieldIdx
    case 1
        field = 'fslewrate';
    case 2
        field = 'rslewrate';
end

if ~isfield(dlgdata.extdata, field)
    dlgdata.extdata.(field).currentElement = 1;
end
currentElement = dlgdata.extdata.(field).currentElement;

switch pageAction

    case {'fallingRateEdit', 'risingRateEdit'}
        rate = deblank(get(Children.(pageAction), 'String'));
        if ~isempty(rate)
            propName = [pageAction(1), 'slewrate'];
            if strcmp(rate, 'ddv')
                if isempty(dlgdata.data.(propName).variable)
                    beep;
                else
                    dlgdata.data.(propName).value = ['ddv(''', dlgdata.data.(propName).variable, ''')'];
                    dlgdata.data.(propName).useddvariablevalue = true;
                end
            else
                dlgdata.data.(propName).value = rate;
            end
            bModified = true;
        else
            beep;
        end

    case 'selectPopup'
        bModified = true;

    case 'maxAccuracyCheckbox'
        dlgdata.data.max_accuracy = get(Children.maxAccuracyCheckbox, 'Value');
        bModified = true;

    case {'fallingRateScalarCheckbox', 'risingRateScalarCheckbox'}
        propName = [pageAction(1), 'slewrate'];
        dlgdata.data.(propName).scalar = get(Children.(pageAction), 'Value');
        % switched fslewrate to scalar => remove all scaling data except
        % those of the currently selected element
        if dlgdata.data.(propName).scalar == 1
            dlgdata.data.(propName).width  = 1;
            dlgdata.data.(propName).lsb    = dlgdata.data.(propName).lsb(currentElement);
            dlgdata.data.(propName).offset = dlgdata.data.(propName).offset(currentElement);
            dlgdata.data.(propName).arb    = dlgdata.data.(propName).arb(currentElement);
            dlgdata.data.(propName).min    = dlgdata.data.(propName).min(currentElement);
            dlgdata.data.(propName).max    = dlgdata.data.(propName).max(currentElement);
            dlgdata.pageData{pageNum}.currentElement = 1;
        end
        bModified = true;

    case 'scaleSlewRateButton'
        options.selectDatatypeSign = 'yes';
        options.minimizeWordWidth  = 'yes';
        ds_error_none;
        [dlgdata.data, bModified, msgstruct] = tl_scale_parameters( ...
            dlgdata.model, dlgdata.data, options, field);
        ds_error_register(msgstruct);
        ds_msgdlg('Update', ...
            'Title', ['Scaling of ' get_tlsubsystempath(dlgdata.model) '->' field], ...
            'ShowErrors', 'yes', ...
            'ShowNotes', 'yes', ...
            'ShowWarnings', 'yes');

    case {'fslewrateDDValueCheckbox', 'rslewrateDDValueCheckbox'}
        propName = [pageAction(1), 'slewrate'];
        if get(Children.(pageAction), 'Value')         
            dlgdata.data.(propName).value = ['ddv(''', dlgdata.data.(propName).variable, ''')'];
            dlgdata.data.(propName).useddvariablevalue = true;
        else
            dlgdata.data.(propName).useddvariablevalue = false;
        end
        bModified = true;

    otherwise
        [dlgdata, bModified1] = ...
            TLManageVariableCtrls('manage',pageNum,dlgfig,dlgdata,pageAction,field);

        [dlgdata,bModified2] = ...
            TLManageScalingCtrls('manage',pageNum,dlgfig,dlgdata,pageAction,field);
        bModified = bModified1 || bModified2;
        
end


%--------------------------------------------------------------------------
% FcnUpdateSlewRatesControls updates the slew rate controls
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnUpdateSlewRatesControls(dlgdata, dlgfig, pageNum)

% default control status
if dlgdata.bIsFullVs
    defaultStatus = 'on';
else
    defaultStatus = 'inactive';
end
fallingRateEditCtrlStatus = struct('enable', 'on');
risingRateEditCtrlStatus  = struct('enable', 'on');
fallingRateScalarCheckboxCtrlStatus = struct('enable', 'on');
risingRateScalarCheckboxCtrlStatus  = struct('enable', 'on');
maxAccuracyCheckboxCtrlStatus = struct('enable', defaultStatus);
selectPopupCtrlStatus = struct( ...
    'enable', 'on', ...
    'value', 1, ...
    'string', {{'falling slew rate'; 'rising slew rate'}});
scaleSlewRateButtonCtrlStatus = struct('enable', defaultStatus);

% determine selected field
Children = dlgdata.pageData{pageNum}.children;
fieldIdx = get(Children.selectPopup, 'Value');
switch fieldIdx
    case 1
        field = 'fslewrate';
        otherField = 'rslewrate';
    case 2
        field = 'rslewrate';
        otherField = 'fslewrate';
end

% update standard controls
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, otherField);
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, field);

% ensure extdata structure exists
if ~isfield(dlgdata, 'extdata') || ~isfield(dlgdata.extdata, 'output')
    dlgdata.extdata.output.currentElement = 1;
end
if ~isfield(dlgdata.extdata, 'fslewrate')
    dlgdata.extdata.fslewrate.currentElement = 1;
end
if ~isfield(dlgdata.extdata, 'rslewrate')
    dlgdata.extdata.rslewrate.currentElement = 1;
end

if strcmp(tl_deblank(dlgdata.data.fslewrate.class, 2), 'default')
    dlgdata.data.fslewrate.scalar = 0;
    fallingRateScalarCheckboxCtrlStatus.enable = 'off';
end
if strcmp(tl_deblank(dlgdata.data.rslewrate.class, 2), 'default')
    dlgdata.data.rslewrate.scalar = 0;
    risingRateScalarCheckboxCtrlStatus.enable = 'off';
end

% handle scalar checkbox: scalarExp is activated (the checkbox is disabled,
% though)
if dlgdata.data.fslewrate.scalar
    dlgdata.extdata.fslewrate.scalarExp = 1;
end
if dlgdata.data.rslewrate.scalar
    dlgdata.extdata.rslewrate.scalarExp = 1;
end

[dlgdata, rate, constraint, errorDescription] = FcnCheckLimit( ...
    dlgdata, otherField, false);

[dlgdata, rate, constraint, errorDescription] = FcnCheckLimit( ...
    dlgdata, field, true, errorDescription);

% evaluate error description and apply to the corresponding edit controls
bCurrentParameterInvalid = errorDescription.(field);

fallingRateScalarCheckboxCtrlStatus.value = dlgdata.data.fslewrate.scalar;
risingRateScalarCheckboxCtrlStatus.value = dlgdata.data.rslewrate.scalar;

selectPopupCtrlStatus.value = fieldIdx;

fallingRateEditCtrlStatus.string = dlgdata.data.fslewrate.value;
if dlgdata.data.fslewrate.useddvariablevalue
    fallingRateEditCtrlStatus.enable = 'inactive';
end
fallingRateEditCtrlStatus.iserror = errorDescription.fslewrate;

risingRateEditCtrlStatus.string = dlgdata.data.rslewrate.value;
if dlgdata.data.rslewrate.useddvariablevalue
    risingRateEditCtrlStatus.enable = 'inactive';
end
risingRateEditCtrlStatus.iserror = errorDescription.rslewrate;

% status of ddv checkboxes
rslewrateDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.rslewrate.variable));
rslewrateDDValueCheckboxCtrlStatus.value = dlgdata.data.rslewrate.useddvariablevalue;
fslewrateDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.fslewrate.variable));
fslewrateDDValueCheckboxCtrlStatus.value = dlgdata.data.fslewrate.useddvariablevalue;

% for parameters there are no simulated ranges.
% Instead, write min/max of rate value
simulatedLabelCtrlStatus = tl_get_control_userdata(Children.simulatedLabel);
upperSimulatedValueCtrlStatus = tl_get_control_userdata(Children.upperSimulatedValue);
lowerSimulatedValueCtrlStatus = tl_get_control_userdata(Children.lowerSimulatedValue);

if dlgdata.extdata.(field).scalarExp
    switch fieldIdx
        case 1
            simulatedLabelCtrlStatus.string = 'of falling rate';
        case 2
            simulatedLabelCtrlStatus.string = 'of rising rate';
    end
else
    simulatedLabelCtrlStatus.string = 'of element';
end

if ~strcmp(tl_deblank(dlgdata.data.(field).class, 2), 'default')
    % fill row with simulated values
    if ~isempty(constraint)
        lowerSimulatedValueCtrlStatus.string = sprintf('%0.6g', min(constraint));
        upperSimulatedValueCtrlStatus.string = sprintf('%0.6g', max(constraint));
    else
        lowerSimulatedValueCtrlStatus.string = 'n.a.';
        upperSimulatedValueCtrlStatus.string = 'n.a.';
    end
    typeString = ['/Pool/Typedefs/' dlgdata.data.(field).type];
    buttonEnable = dlgdata.bIsFullVs & ~bCurrentParameterInvalid & all(isfinite(constraint)) & ...
        ds_isa(typeString, 'integertype') & ...
        ~ds_isa(typeString, 'constrainedtype');
    scaleSlewRateButtonCtrlStatus.enable = flag2str(buttonEnable);
else
    scaleSlewRateButtonCtrlStatus.enable = 'off';
end

scalarExpCheckboxCtrlStatus = tl_get_control_userdata(Children.scalarExpCheckbox);
if dlgdata.data.(field).scalar
    scalarExpCheckboxCtrlStatus.enable = 'off';
end

maxAccuracyCheckboxCtrlStatus.value = dlgdata.data.max_accuracy;

% write back to UserData
extraCtrlsList = {
    'fallingRateEdit' ...
    'fallingRateScalarCheckbox' ...
    'risingRateEdit' ...
    'risingRateScalarCheckbox' ...
    'scaleSlewRateButton' ...
    'selectPopup' ...
    'maxAccuracyCheckbox' ...
    'rslewrateDDValueCheckbox' ...
    'fslewrateDDValueCheckbox'};
standardCtrlsList = {
    'scalarExpCheckbox' ...
    'simulatedLabel' ...
    'simulatedLabel' ...
    'upperSimulatedValue' ...
    'lowerSimulatedValue'};
ctrlsList = [extraCtrlsList standardCtrlsList];
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of standard controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

% set status of rate controls
TLSetCtrlsStatus(dlgfig, Children, extraCtrlsList)


%--------------------------------------------------------------------------
% FcnCheckLimit checks the constraints on limits
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   field       current field
%   bVisible    flag =1, if field has scaling controls, =0 otherwise
%   errorDescription    structure of error flags
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   limit       limit
%   constraint  constraint
%   errorDescription    structure of error flags
%--------------------------------------------------------------------------
function [dlgdata, limit, constraint, errorDescription] = ...
    FcnCheckLimit(dlgdata, field, bVisible, errorDescription)

if nargin == 3
    errorDescription = struct();
end

[limit, constraint, bCompliant] = ...
    tl_get_param_constraints(dlgdata.data.(field), dlgdata.extdata.(field));

pageNum = 2;
if bVisible
    % update controls for currently displayed field
    dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, field, constraint);
end

errorDescription.(field) = ~bCompliant;
